<?php
namespace app\admin\controller;
use Symfony\Component\Yaml\Tests\A;
use think\Controller;
use app\model\MenuModel;
use app\model\UserModel;
use app\model\DeviceModel;
use app\model\AppUserModel;
use app\model\EquipmentModel;
use app\model\DeviceInfoModel;
/**
 * Created by PhpStorm.
 * User: 郑合达
 * Date: 2019/1/21
 * Time: 14:55
 */
class User extends Common
{
    /**
     * @return \think\response\View
     * 用户首页
     */
    public function index(){

        $int = input('int',1);//区分设备，下级客户，资料
        $this->assign('int',$int);
        return view('index');
    }


    /*
     * 测试无限目录
     */
    public function menu()
    {
        $int = input('int',1);
        $this->assign('int',$int); //状态选定、
        $menu_id=input('menu_id');//用户名称id
        $mid = MenuModel::where('user_id',session('user.id'))->value('id'); //获取登陆的用户名称id
        if ($menu_id){   //判断是否第一次登陆
            $user_id = MenuModel::where('id',$menu_id)->value('user_id');
            $wuser['a.id']=$user_id;
            $where['user_id']=$user_id;
            $uid =$user_id;
        }else{
            $wuser['a.id']=session('user.id');
            $where['user_id']=session('user.id');
            $uid =session('user.id');
            $menu_id=$mid;
        }

        $type =AppUserModel::where('id',$uid)->value('type');//判断选择的是否是管理员账号
        $this->assign('type',$type);
        $arr=MenuModel::select();//全部数据
        $array=MenuModel::where('id',$mid)->select();//根目录数据
        $shu= $this->shu($arr,$array);//数组形式呈现
        $data['menu']= $this->shu2($shu,$menu_id);//html代码呈现

    //用户信息数据 及 资料
        $user =AppUserModel::alias('a')->field('a.*')
            ->field('m.name')
            ->join('gps_menu m','m.user_id = a.id')
            ->where($wuser)
            ->find();
        $count =EquipmentModel::where('equ_user',$uid)->count();//设备数量
        $this->assign('count',$count);
        $this->assign('res',$user);



     //下级客户数据
         $m_id = MenuModel::where($where)->value('id');//登陆的用户名称id
        $list = MenuModel::alias('m')->field('m.*,m.id as mid')
            ->field('a.*')
            ->join('gps_app_user a','a.id = m.user_id','left')
            ->where('m.follow_id','=',$m_id)
            ->paginate(7,false,['query'=>request()->param()]);
//        dump($list->toArray());die();
      $this->assign('list',$list); //下级客户数据

        //设备信息
        $kehu =AppUserModel::alias('a')->field('a.phone,a.add_time,a.add_time,a.id')
              ->field('e.name,e.nickname,e.expire_time')
              ->join('gps_equipment e','e.equ_user = a.id')
              ->where('a.id',$uid)
            ->paginate(7,false,['query'=>request()->param()]);

        $this->assign('user_id',$uid);
         $this->assign('kehu',$kehu);

        return view('user/menu',$data);
    }
     //用户新增页面
    public function adduser(){
        $menu_id = input('menu_id');
//        $mid = MenuModel::where('user_id',session('user.id'))->value('id'); //获取登陆的用户名称id
        $user_id =AppUserModel::where('type',1)->column('id'); //所有管理员的账号id
        $arr=MenuModel::where('user_id','in',$user_id)->select();//全部管理的数据
        $array=MenuModel::where('id',$menu_id)->select()->toArray();//根目录数据
        $shu= $this->shu($arr,$array);//数组形式呈现
        $data['menu']= $this->shu2($shu,$menu_id);//html代码呈现

        $name =MenuModel::where('id',$menu_id)->value('name');
        $this->assign('follow_id',$menu_id);
        $this->assign('name',$name);
        return view('adduser',$data);
    }
    //用户新增功能
    public function roleadd(){
        $data = (input('post.'));
        $menu=[];
        $menu['name'] = $data['nickname'];
        $menu['follow_id'] =$data['follow_id'];
         unset($data['follow_id']);unset($data['user_passvr']);
         $phone =AppUserModel::where('phone',$data['phone'])->count();
         if($phone){
             return retJson('', 201, '账号已存在');
         }
        $data['password'] =encryptPass( $data['password']);//密码加密
        $data['type'] =1;
        $res =AppUserModel::create($data);
        if($res->id){
            $menu['user_id']=$res->id;
            $info =MenuModel::create($menu);
            if($info){
                return retJson('', 200, '新增成功');
            }
            return retJson('', 201, '新增失败');
        }
        return retJson('', 201, '新增失败');
    }
    //修改资料
    public function editzl(){
        $data=input('post.');
        $id =$data['id'];
        if($data['password']||$data['passworder']){
            if(!$data['passworder']){
                return retJson('', 201, '确认密码为空');
            }
            if($data['password']!=$data['passworder']){
                return retJson('', 201, '两次密码不一致');
            }
        }

        unset($data['id']);unset($data['passworder']);

        if(!$data['password']){
            unset($data['password']);
        }else{
            $data['password']=encryptPass($data['password']);
        }

        $men['name']=$data['nickname'];
        $info =MenuModel::update($men,['user_id'=>$id]);
       $res = AppUserModel::update($data,['id'=>$id]);
        if($res){
            return retJson('', 200, '修改成功');
        }
        return retJson('', 201, '修改失败');
    }
    //删除下级客户
    public function delete(){
        $mid =input('mid');
        $user_id =input('user_id');
       $res = MenuModel::where('follow_id',$mid)->select()->toArray();
       if($res){
           return retJson('',201,'该用户下有别的用户,不能删除!');
       }
       $info = MenuModel::destroy($mid);
       $user = AppUserModel::destroy($user_id);
       if($info&&$user){
           return retJson('',200,'删除成功');
       }else{
           return retJson('',201,'删除失败');
       }

    }
    //管理用户
    public function edituser(){
        $user_id =input('user_id');
        $user =AppUserModel::alias('a')->field('a.*')
            ->field('m.name, m.id as mid')
            ->join('gps_menu m','m.user_id = a.id')
            ->where('a.id',$user_id)
            ->find()
            ->toArray();
        $this->assign('res',$user);
        return view('edituser');
    }
 //修该用户信息
    public function edit(){
        $data=input('post.');
       $menu =MenuModel::update(['name'=>$data['nickname']],['id'=>$data['mid']]);
        $id =$data['id'];
        unset($data['id']);unset($data['mid']);
        $res = AppUserModel::update($data,['id'=>$id]);
        if($res){
            return retJson('', 200, '修改成功');
        }
        return retJson('', 201, '修改失败');
    }


 public function editkehuo(){
        $id=input('id');
        $data =DeviceModel::where('id',$id)->find()->toArray();
        $this->assign('data',$data);
        return view('editkehuo');
 }
 public function kehu(){
     $data=input('post.');
     $id =$data['id'];
     unset($data['id']);
     $menu =DeviceModel::update($data,['id'=>$id]);
     if($menu){
         return retJson('', 200, '修改成功');
     }
     return retJson('', 201, '修改失败');
 }
    //转移客户页面
    public function transfer(){
        $menu_id = input('menu_id');
        $id =input('test_list');
        //目录数据
        $mid = MenuModel::where('user_id',session('user.id'))->value('id'); //获取登陆的用户名称id
        $user_id =AppUserModel::where('type',1)->column('id'); //所有管理员的账号id
        $arr=MenuModel::where('user_id','in',$user_id)->select();//全部管理的数据
        $array=MenuModel::where('id',$mid)->select();//根目录数据
        $shu= $this->shu($arr,$array);//数组形式呈现
        $data['menu']= $this->shu2($shu,$menu_id);//html代码呈现
        //目标客户名称
        $name =MenuModel::where('id',$menu_id)->value('name');
        $this->assign('follow_id',$menu_id);
        $this->assign('name',$name);
        //设备编号（数组）
        $this->assign('ids',$id);
         //要转移的客户数据
        $list = AppUserModel::where('id','in',$id)->select();

         $this->assign('list',$list);
     return view('transfer',$data);
    }
   //转移用户功能
    public function transferedit(){
        $data =input('post.');
        if(!$data['ids']){
            return retJson('', 201, '请选择设备');
        }
        $id = explode(",", $data['ids']);
        foreach ($id as $key => $v){
            $info =MenuModel::update(['follow_id'=>$data['men_id']],['user_id'=>$v]);
         }
        if($info){
            return retJson('', 200, '转移成功');
        }
        return retJson('', 201, '转移失败');
    }




    /*
     * 无限目录html
     * $shu 目录树形结构
     * $menu_id 目录名称id(用户名称id)
     * 返回html代码
     */
    public function shu2($shu,$menu_id)
    {
        $data=$shu;
        $html='';
        foreach ($data as $k=>$v){
            //判断是否高亮
            if($menu_id ==$v['id']){
                $htmls='<li data-jstree={"type":"img"} menu_id="'.$v['id'].'"><a class="jstree-clicked" href="#" >'.$v['name'].'</a></li>';
                $htmls1='<a class="jstree-clicked" href="#" >'.$v['name'].'</a>';
            }else{
                $htmls='<li data-jstree={"type":"img"} menu_id="'.$v['id'].'">'.$v['name'].'</li>';
                $htmls1=$v['name'];
            }
            if (empty($v['menu'])){//个体(空)
                $html.=$htmls;
            }else{//目录
                $html2=$this->shu2($v['menu'],$menu_id);
                $html.=' <li class="jstree-open" menu_id="'.$v['id'].'">';//jstree-open  目录状态--开启（删除为关闭）
                $html.=    $htmls1;
                $html.='    <ul>';
                $html.=         $html2; //填充子目录
                $html.='    </ul>';
                $html.='</li>';
            }

        }
        return $html;
    }


    /*
   * 生成无限树形数组
   * $arr 总数据
   * $array 母目录数据（调用本方法放最大一层目录）
   *        重复调用时填该层的数据
   */
    public function shu($arr,$array)
    {
        $data=$array;
        foreach ($array as $k=>$v){
            $data2=[];
            foreach ($arr as $key=>$value){
                if ($value['follow_id']==$v['id']){//找到子目录（follow_id指向母目录id）
                    array_push($data2,$value);//把目录放入母目录的"menu"下
                }
                $data2 = $this->shu($arr,$data2);
                $data[$k]['menu']=$data2;
            }
        }
        return $data;
    }


    //报表导出
    public function export(){
      $user_id = input('user_id');
//      dump($user_id);die();
        $data =DeviceModel::field('*')->where('user_id',$user_id)->order('id')->select();
        //表头
        $header = ['序号','设备名称','设备号（ID）','设备手机卡号','创建时间','激活时间','到期时间'];
        //用于遍历的二维数组
        $result_data=array();
        for($i=0;$i<count($data);$i++){
            $new = array();
            $new[] =  $data[$i]['id'];
            $new[] =  $data[$i]['de_name'];
            $new[] =  $data[$i]['Devid'];
            $new[] =  $data[$i]['de_phone'];
            $new[] =  $data[$i]['creation_time'];
            $new[] =  $data[$i]['activation_time'];
            $new[] =  $data[$i]['due_time'];
            array_push($result_data,$new);
        }
        //$filename 文件名
        $filename = "设备列表".date("Y/m/d");
//        ExcelModel::getExcelFile(NULL,$header,$result_data,$filename,30);
        export($result_data, $header, $filename);
    }
}